package org.zjvis.datascience.web.shiro;

import java.util.Collections;
import java.util.Set;
import org.apache.shiro.authc.AccountException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.zjvis.datascience.common.dto.user.UserDTO;
import org.zjvis.datascience.service.UserService;

/**
 * @description : Jwt 规则类
 * @date 2020-06-01
 */
@Component
public class JwtRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    /**
     * 限定这个 Realm 只处理我们自定义的 JwtToken
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }

    /**
     * 此处的 SimpleAuthenticationInfo 可返回任意值，密码校验时不会用到它
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken)
            throws AuthenticationException {
        JwtToken jwtToken = (JwtToken) authcToken;
        if (jwtToken.getPrincipal() == null) {
            throw new AccountException("JWT token参数异常！");
        }
        String userName = jwtToken.getPrincipal().toString();
        try {
            UserDTO user = userService.queryByName(userName);
            if (user == null) {
                throw new AccountException("JWT token参数异常！");
            }
            return new SimpleAuthenticationInfo(user, jwtToken.getCredentials(), "");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 权限检查
     *
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        UserDTO user = (UserDTO) principals.getPrimaryPrincipal();
        Set<String> permissionsSet = Collections.EMPTY_SET;
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setStringPermissions(permissionsSet);
        return info;
    }

}
